// 认证相关功能
class AuthManager {
    constructor() {
        this.isLoggedIn = false;
        this.currentUser = null;
        this.sessionKey = 'lumina_admin_session';
        this.init();
    }

    init() {
        // 检查是否已登录
        this.checkLoginStatus();
        
        // 绑定登录表单事件
        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => this.handleLogin(e));
        }
    }

    // 检查登录状态
    checkLoginStatus() {
        const session = this.getSession();
        if (session && session.expiresAt > Date.now()) {
            this.isLoggedIn = true;
            this.currentUser = session.user;
            // 如果已登录且当前在登录页，则跳转到后台首页
            if (window.location.pathname.includes('login.html')) {
                window.location.href = 'index.html';
            }
        } else {
            // 清除过期会话
            this.clearSession();
        }
    }

    // 处理登录
    async handleLogin(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const remember = document.getElementById('remember').checked;

        if (!username || !password) {
            this.showError('请输入用户名和密码');
            return;
        }

        // 显示加载状态
        const submitBtn = e.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>登录中...';
        submitBtn.disabled = true;

        try {
            // 模拟登录验证（实际项目中应该调用后端 API）
            const success = await this.validateCredentials(username, password);
            
            if (success) {
                // 登录成功
                this.login(username, remember);
                window.location.href = 'index.html';
            } else {
                this.showError('用户名或密码错误');
            }
        } catch (error) {
            this.showError('登录失败，请稍后重试');
            console.error('Login error:', error);
        } finally {
            // 恢复按钮状态
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    // 验证凭据（模拟）
    async validateCredentials(username, password) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 简单的硬编码验证（实际项目中应该调用后端 API）
        const validCredentials = {
            'admin': 'admin123',
            'editor': 'editor123'
        };
        
        return validCredentials[username] === password;
    }

    // 登录
    login(username, remember = false) {
        this.isLoggedIn = true;
        this.currentUser = { username, role: username === 'admin' ? 'admin' : 'editor' };
        
        // 创建会话
        const session = {
            user: this.currentUser,
            expiresAt: remember ? Date.now() + (7 * 24 * 60 * 60 * 1000) : Date.now() + (24 * 60 * 60 * 1000)
        };
        
        this.setSession(session);
        
        // 触发登录成功事件
        window.dispatchEvent(new CustomEvent('loginSuccess', { detail: this.currentUser }));
    }

    // 登出
    logout() {
        this.isLoggedIn = false;
        this.currentUser = null;
        this.clearSession();
        
        // 跳转到登录页（兼容嵌套路径）
        try {
            const parts = window.location.pathname.split('/admin/');
            const base = parts[0] + '/admin/';
            window.location.href = base + 'login.html';
        } catch (e) {
            window.location.href = 'login.html';
        }
    }

    // 获取会话
    getSession() {
        try {
            const sessionStr = localStorage.getItem(this.sessionKey);
            return sessionStr ? JSON.parse(sessionStr) : null;
        } catch (error) {
            console.error('Error parsing session:', error);
            return null;
        }
    }

    // 设置会话
    setSession(session) {
        try {
            localStorage.setItem(this.sessionKey, JSON.stringify(session));
        } catch (error) {
            console.error('Error saving session:', error);
        }
    }

    // 清除会话
    clearSession() {
        try {
            localStorage.removeItem(this.sessionKey);
        } catch (error) {
            console.error('Error clearing session:', error);
        }
    }

    // 显示错误信息
    showError(message) {
        const errorModal = document.getElementById('errorModal');
        const errorMessage = document.getElementById('errorMessage');
        
        if (errorModal && errorMessage) {
            errorMessage.textContent = message;
            errorModal.classList.remove('hidden');
            errorModal.classList.add('flex');
        }
    }

    // 检查权限
    hasPermission(permission) {
        if (!this.isLoggedIn || !this.currentUser) {
            return false;
        }
        
        // 简单的权限检查（实际项目中应该有更复杂的权限系统）
        if (this.currentUser.role === 'admin') {
            return true; // 管理员拥有所有权限
        }
        
        // 编辑者权限
        const editorPermissions = ['blog:read', 'blog:write', 'blog:edit'];
        return editorPermissions.includes(permission);
    }
}

// 关闭错误弹窗
function closeErrorModal() {
    const errorModal = document.getElementById('errorModal');
    if (errorModal) {
        errorModal.classList.add('hidden');
        errorModal.classList.remove('flex');
    }
}

// 初始化认证管理器
const authManager = new AuthManager();

// 导出供其他模块使用
window.AuthManager = AuthManager;
window.authManager = authManager;
